package org.scboy.common.interceptors;

import org.scboy.common.cache.SystemConfig;
import org.scboy.common.properties.CommonProperties;
import org.scboy.common.request.CacheRequest;
import org.scboy.common.request.CacheResponse;
import org.scboy.common.service.LoggerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;

import cn.hutool.http.ContentType;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Configuration
public class LoggerInterceptor  implements HandlerInterceptor {

	Log log=LogFactory.get();
	
	@Autowired
	LoggerService service;
	

	@Autowired
	CommonProperties properties;
	
	@Autowired
	SystemConfig config;
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			@Nullable Exception ex) throws Exception {
		//优先判断是否开启了请求日志记录
		if(config!=null) {
			//如果关闭了日志记录，不用记录日志信息。
			if("CLOSE".equals(config.getConfig("LOGGER_OPEN_REQUEST_LOG"))) {
				return;
			}
		}
		
		//如果开启日志记录
		if(properties.isOpenRequestLog()) {
			if(ex!=null) {
				log.error(ex);
				return;
			}
			//只记录JSON格式的数据
			if(handler instanceof HandlerMethod && ContentType.JSON.toString().equals(response.getContentType()) && ContentType.JSON.toString().equals(response.getContentType())) {
				HandlerMethod method = (HandlerMethod)handler;
		        CacheRequest requestCache=WebUtils.getNativeRequest(request, CacheRequest.class);
		        CacheResponse responseCache = WebUtils.getNativeResponse(response, CacheResponse.class);
		        service.writeRequestLog(requestCache, responseCache,method);
		    }
		}
	}
}
